const router = require( 'koa-router' )();
const path = require( 'path' );
const fs = require( 'fs' );
const DateMath = require('date-arithmetic');

const akUtil = require( '../utils/ak_utils' );

const userTable = require( '../models/user' );
const userPlanTable = require( '../models/user_plan' );
const apiKeyTable = require( '../models/api_key' );
const planTable = require( '../models/plan' );
const accountConfirmTable = require( '../models/account_confirm' );
const orderResetpwdTable = require( '../models/order_resetpwd' );
const userConsumeTable = require('../models/user_consume');
const config = require( '../config' );

const headers = { 'Content-Type': 'application/json', 'Encoding': 'utf8' };


// const sign = async function ( ctx, next ) {
//     return ctx.render( 'sign' );
// }

const confirm = async function ( ctx, next ) {
    let key = ctx.params.key;
    let email = ctx.query.email;

    let status = 'invalid';

    if ( !key || !email ) {
        status = 'invalid';
    } else {
        let confirm = await accountConfirmTable.getByKey( key );
        if ( !confirm || confirm.length === 0 || confirm[ 0 ].confirmed ) {
            status = 'invalid';
        } else {

            let userId = confirm[ 0 ].user_id;

            let result = await userTable.getUser( userId );
            let user = result[ 0 ];

            if ( email !== user.email ) {
                status = 'invalid';
            } else {

                try {

                    await userTable.updateConfirmed( userId, true );

                    await accountConfirmTable.updateConfirmed( key, true );

                    // add user consume

                    let result = await userConsumeTable.getByUserId(userId);

                    // 如果没有user consume记录，则新建一条记录

                    if(!result){

                        let startAt = user.created_at;
                        let endAt = DateMath.add(startAt, 1, 'month');

                        await userConsumeTable.create(userId, 'free', 0, 0, 0, startAt, endAt);

                    }

                    status = 'valid';

                } catch ( e ) {

                    status = 'fail';

                }
            }

        }
    }

    return ctx.render( 'confirm', {
        status,
        email,
        page: JSON.stringify(config.page)
    } );
}

const resetPwd = async function ( ctx, next ) {
    let key = ctx.query.key;
    let email = ctx.query.email;

    let status = 'invalid';

    if ( !email || !key ) {
        status = 'invalid';

        return ctx.render( 'reset_pwd', {
            status,
            page: JSON.stringify(config.page)
        } );

    }

    let order = await orderResetpwdTable.getTodoOrder( email, key );
    if ( order && order.length > 0 ) {
        let result = await userTable.getUserByEmail( email );
        let user = result[ 0 ];

        let key = order[ 0 ].key;

        status = 'valid';
        return ctx.render( 'reset_pwd', {
            status,
            email,
            key,
            page: JSON.stringify(config.page)
        } );
    }


    status = 'invalid';
    return ctx.render( 'reset_pwd', {
        status,
        email,
        page: JSON.stringify(config.page)
    } );
}


// router.get( '/sign', sign );
router.get( '/confirm/:key', confirm );
router.get( '/reset_pwd', resetPwd );

module.exports = router;
